<!--部门管理-->
<template>
  <section class="app-container">
    <div class="content">
      <div class="content-head">
        <el-row>
          <el-col :span="24">
            <el-form :inline="true" :model="queryData" class="demo-form-inline">
              <el-form-item label="关键字">
                <el-input v-model.trim="queryData.roleName" class="width-150" placeholder="请输入角色名称关键字" clearable @keyup.enter.native="getTableList(true)" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" icon="el-icon-search" @click="getTableList(true)">查询</el-button>
                <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="reset()">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-button v-p="'departmentManageAdd'" type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')">新增部门</el-button>

          </el-col>
          <el-col :span="8" class="text-right">
            <div>
              <el-link icon="fa fa-question-circle-o" @click="help">帮助说明</el-link>
              <!-- <el-button size="small" @click="Utils.building">手动排序</el-button>
              <el-button size="small" @click="Utils.building">按字母排序</el-button> -->
            </div>
          </el-col>
        </el-row>
      </div>
      <!--列表 -->
      <el-table
        v-loading="tableListLoading"
        :data="tableList"
        row-key="orgId"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
        height="600"
        size="small"
        stripe
        border
      >
        <el-table-column type="index" label="序号" width="46" fixed />
        <el-table-column prop="orgName" label="部门名称" min-width="120" sortable />
        <el-table-column prop="userList" label="人员数量" min-width="100" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.userList.length }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="部门描述" min-width="100" sortable show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" min-width="136" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime | formatDateToStr }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="70" sortable>
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" disabled active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="300" fixed="right">
          <template slot-scope="scope">
            <a v-p="'departmentManageupdate'" href="javascript:;" class="text-blue inline-block" @click="openDialog('edit',scope.row)"><i class="el-icon-edit" />编辑部门</a>
            <a v-p="'departmentManageIsUse'" href="javascript:;" class="text-blue inline-block" @click="switchStaus(scope.row)"><i class="el-icon-remove" />{{ scope.row.status===1?'停用':'启用' }}部门</a>
            <a v-p="'departmentManageDelete'" href="javascript:;" class="text-danger inline-block" @click="deleteItem(scope.row)"><i class="el-icon-delete" />删除部门</a>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div>
      <!--新增/修改-弹窗  -->
      <el-dialog :title="dialogType=='add'?'新增部门':'修改部门'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false" @opened="listenOpenedDialog" @closed="listenClosedDialog">
        <el-form ref="dialogFormData" :model="dialogFormData" label-width="160px" :rules="dialogFormDataRules">
          <el-form-item label="上级部门:" prop="parentId">
            <el-cascader
              v-model="dialogFormData.parentId"
              :options="departmentList"
              :props="{ expandTrigger: 'hover',value: 'orgId',label: 'orgName',checkStrictly: true }"
              placeholder="请选择,不选表示顶级"
            />
          </el-form-item>
          <el-form-item label="部门名称:" prop="orgName">
            <el-input v-model.trim="dialogFormData.orgName" placeholder="请输入部门名称" clearable maxlength="50" />
          </el-form-item>

          <el-form-item label="启用状态:" prop="status">
            <el-select v-model="dialogFormData.status">
              <el-option :value="1" label="启用" />
              <el-option :value="0" label="关闭" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门描述:" prop="description">
            <el-input v-model.trim="dialogFormData.description" type="textarea" placeholder="在此输入描述信息" maxlength="300" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormDataSubmit('dialogFormData')">立即提交</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>

<script>
import { queryAllOrgTree, addOrg, updateOrg, isUseOrg, deleteOrg } from '@/api/api'

export default {
  data() {
    return {
      tableListLoading: false,

      // 查询表单数据
      queryData: {
        roleName: ''
      },

      // 表格数据
      tableList: [],
      // 新增/修改弹窗相关数据
      dialogVisible: false,
      dialogType: 'add',
      // 表单数据
      dialogFormData: {
        parentId: '',
        orgName: '',
        status: 1,
        description: ''
      },
      // 表单数据验证
      dialogFormDataRules: {
        orgName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },
      // 部门数据,用户渲染下拉选,从store获取
      departmentList: []

    }
  },
  mounted() {
    this.getTableList(false)
  },
  methods: {
    /**
     * 查询
     * @param {(Boolean)} isFirst  是否从第1页开始查询
     */
    getTableList(isFirst) {
      this.tableListLoading = true
      queryAllOrgTree({}).then(res => {
        this.tableListLoading = false

        if (res.code === '0000') {
          this.tableList = res.data
        }

      // eslint-disable-next-line handle-callback-err
      }).catch(error => {
        this.tableListLoading = false
      })
    },
    /**
     * 打开新增/编辑弹窗
     * @param {(String)} type  弹窗类型,"add=新增,edit=修改"
     * @param {(Object)} row  操作行数据,修改时传
     */
    openDialog(type, row) {
      const tempList = this.Utils.deepCopy(this.$store.getters.departmentList)
      // 去除children为"[]"的字段
      this.departmentList = this.Utils.isHasChildren(tempList)

      this.dialogType = type
      this.dialogVisible = true
      if (type === 'edit') {
        // 获取当前部门的父级id
        this.dialogFormData.parentId = this.Utils.getParentIdList(row.orgId, this.departmentList, 'orgId')
        this.dialogFormData.orgId = row.orgId
        this.dialogFormData.orgName = row.orgName
        this.dialogFormData.status = row.status
        this.dialogFormData.description = row.description
      }
    },
    listenOpenedDialog() {

    },
    listenClosedDialog() {
      // 初始化表单状态
      this.$refs['dialogFormData'].resetFields()
      this.Utils.emptyObject(this.dialogFormData)
      this.dialogFormData.status = 1
    },
    // 新增编辑弹窗表单提交
    dialogFormDataSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = this.Utils.deepCopy(this.dialogFormData)
          if (this.dialogFormData.parentId && this.dialogFormData.parentId.length) {
            // 因有多个值,取直接上级,即最后一个
            params.parentId = this.dialogFormData.parentId[this.dialogFormData.parentId.length - 1]
          } else {
            params.parentId = 0
          }
          if (this.dialogType === 'add') {
            addOrg(params).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(true)
                this.$store.dispatch('api/getDepartmentList')
              }
            })
          } else {
            if (params.parentId === params.orgId) {
              this.$alert('上级不能选择自己')
              return
            }
            // 获取所修改部门的所有子级id
            const tempSet = new Set(this.Utils.getChildrenIdList(params.orgId, this.$store.getters.departmentList))

            if (tempSet.has(params.parentId)) {
              this.$alert('不能选择自己子级部门')
              return
            }

            updateOrg(params).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(false)
                this.$store.dispatch('api/getDepartmentList')
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置搜索条件
    reset() {
      this.queryData = this.Utils.emptyObject(this.queryData)
    },
    // 切换启用状态
    switchStaus(row) {
      const params = {
        orgId: row.orgId,
        status: Number(!row.status)
      }
      const operatType = row.status === 1 ? '停用' : '启用'
      this.$confirm(`您确定要${operatType}部门"${row.orgName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isUseOrg(params).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
            this.$store.dispatch('api/getDepartmentList')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 删除
    deleteItem(row) {
      this.$confirm(`您确定要删除部门"${row.orgName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrg({ orgId: row.orgId }).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
            this.$store.dispatch('api/getDepartmentList')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    help() {
      this.$alert(`
        1、公司组织架构非常重要，部分管理功能以及数据权限是依赖于公司组织架构的，因此建议在正式使用产品前进行相关配置；</br>
        2、部门组织架构支持多级、最多支持5级，点击左侧层级列表可切换至查看对应部分的子级部门；</br>
        3、需要删除部门时必须先清除该部分下的所有成员；</br>
      `, '帮助说明', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    }

  }
}
</script>
<style lang="scss" scoped>

</style>
